package huadi.android.sudoku;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class GameActivity extends Activity {

	public static final String LOG_TAG = "GameActivity";
	public static final String DIFFICULTY_KEY = "huadi.android.sudoku.GameActivity";
	public static final int DIFFICULTY_EASY = 0;
	public static final int DIFFICULTY_MEDIUM = 1;
	public static final int DIFFICULTY_HARD = 2;

	public int[] puzzle = new int[9 * 9];

	private PuzzleView pv;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(LOG_TAG, "on create");
		int diff = this.getIntent()
				.getIntExtra(DIFFICULTY_KEY, DIFFICULTY_EASY);
		puzzle = getPuzzle(diff);
		pv = new PuzzleView(this);
		setContentView(pv);
		pv.requestFocus();
	}

	/**
	 * generate a puzzle with difficulty.
	 * 
	 * @param diff
	 *            difficulty(0-easy, 1-medium, 2-hard)
	 * @return 9 * 9 int array.
	 */
	private int[] getPuzzle(int diff) {
		String s = "360000000004230800000004200"
				+ "070460003820000014500013020" + "001900000007048300000000045";
		return this.fromPuzzleString(s);
	}

	public String getTileString(int i, int j) {
		return String.valueOf(puzzle[j * 9 + i]);
	}

	public int getTile(int x, int y) {
		return puzzle[y * 9 + x];
	}

	public void setTile(int x, int y, int value) {
		puzzle[y * 9 + x] = value;
	}

	// 游戏逻辑
	protected boolean setTileIfValid(int x, int y, int value) {
		int tiles[] = getUsedTiles(x, y);
		if (value != 0) {
			for (int tile : tiles) {
				if (tile == value)
					return false;
			}
		}
		setTile(x, y, value);
		calculateUsedTiles();
		return true;
	}

	private final int used[][][] = new int[9][9][];

	protected int[] getUsedTiles(int x, int y) {
		return used[x][y];
	}

	private void calculateUsedTiles() {
		for (int x = 0; x < 9; x++) {
			for (int y = 0; y < 9; y++) {
				used[x][y] = calculateUsedTiles(x, y);
			}
		}
	}

	private int[] calculateUsedTiles(int x, int y) {
		int c[] = new int[9];
		for (int i = 0; i < 9; i++) {
			if (i == y)
				continue;
			int t = getTile(x, i);
		}
		return null;
	}

	// save
	private String toPuzzleString() {
		StringBuilder sb = new StringBuilder();
		for (int i : this.puzzle) {
			sb.append(i);
		}
		return sb.toString();
	}

	// load
	private int[] fromPuzzleString(String p) {
		int[] puz = new int[p.length()];
		for (int i = 0; i < p.length(); i++) {
			puz[i] = p.charAt(i) - '0';
		}
		return puz;
	}
}
